package com.freemarker.pickdata;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.freemarker.db.JDBCUtil;
import com.freemarker.db.SpringUtil;
import com.freemarker.db.StringUtil;

import freemarker.template.Configuration;
import freemarker.template.Template;

public class DocHandler {

	public static String templatePath = "/com/test/freemarker/template";
	public static String file_out_path = "D:/freemarker";
	public static String charsetName = "UTF-8";

	private Configuration configuration = null;

	public DocHandler() {
		this.configuration = new Configuration();
		this.configuration.setDefaultEncoding(charsetName);
	}

	public static Map getDataMap(String tableName, String table_schema, String clazzName, String sql) throws Exception {
		Map dataMap = new HashMap();
		List<Map> columnList = JDBCUtil.getListByMap(sql, new Object[] { tableName, table_schema });
		String tabComment = JDBCUtil.getString(SpringUtil.getData("tabComment"), new Object[] { tableName, table_schema });

		// String tabComment = "";
		dataMap.put("columnList", columnList);
		dataMap.put("tableName", tableName);
		dataMap.put("clazzName", clazzName);
		dataMap.put("tabComment", StringUtil.trim(tabComment));
		dataMap.put("nowDate", StringUtil.getDate());
		return dataMap;
	}

	public static void main(String[] args) throws Exception {
		
//		DataTransterVO vo=new DataTransterVO("bee_activity_father2016");
//		Map otherMap=new HashMap();
//		otherMap.put("name", "zhangsan");
//		otherMap.put("age", "20");
//		vo.setOtherMap(otherMap);
//		
//		new DocHandler().init("");
	}

	public void init(String path) throws Exception {
		configuration.setClassForTemplateLoading(DocHandler.class, templatePath);

		File newsDir = new File(path);
		if (!newsDir.exists()) {
			newsDir.mkdirs();
		}
	}

	public void build(Map dataMap, String fileName, String templateName) throws Exception {

		System.out.println("------------文件名称 [ " + fileName + " ] ----------------");
		System.out.println(dataMap.toString());

		init(file_out_path);

		Template template = null;
		Writer writerOut = null;
		FileOutputStream fos = null;
		try {
			template = configuration.getTemplate(templateName,charsetName);
			
			fos=new FileOutputStream(new File(file_out_path, fileName));
			writerOut = new BufferedWriter(new OutputStreamWriter(fos, charsetName));
			
			template.process(dataMap, writerOut);
			
			System.out.println("=============[ " + fileName + " ] 生成成功=============");
			
		} catch (Exception e) {
			System.err.println("=============[ " + fileName + " ] 生成失败=============");
			e.printStackTrace();
		} finally {
			if (writerOut != null) {
				writerOut.close();
			}
			if (fos != null) {
				fos.close();
			}
		}
	}

}